package com.letv.app.ljodfh.utils;

import android.content.Context;
import android.media.MediaMetadataRetriever;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;

import com.jiongbull.jlog.JLog;
import com.qiniu.pili.droid.shortvideo.PLShortVideoTranscoder;
import com.qiniu.pili.droid.shortvideo.PLVideoSaveListener;

import java.io.File;

import static com.qiniu.pili.droid.shortvideo.PLErrorCode.ERROR_LOW_MEMORY;
import static com.qiniu.pili.droid.shortvideo.PLErrorCode.ERROR_NO_VIDEO_TRACK;
import static com.qiniu.pili.droid.shortvideo.PLErrorCode.ERROR_SRC_DST_SAME_FILE_PATH;


/**
 * Author: create by Administrator on 2018/6/28 10 19
 * Des:
 */
public class VideoCompressUtils {

    private static VideoCompressUtils instance;
    //3分钟最大的视频大小比
    private static final double COMPRESS_B = 300 * 1024 * 1024 / (3 * 60 * 1000);

    private static final double SIZE_300 = 300 * 1024 * 1024;
    private static final double SIZE_150 = 150 * 1024 * 1024;
    private static final double SIZE_50 = 50 * 1024 * 1024;
    //压缩成功
    public static final int COMPRESS_SUCCESS = 0;
    //该文件没有视频信息
    public static final int COMPESS_ERROR_NO_VIDEO_TRACK = 1;
    //源文件路径和目标路径不能相同
    public static final int COMPRESS_ERROR_SRC_DST_SAME_FILE_PATH = 2;
    //手机内存不足，无法对该视频进行时光倒流
    public static final int COMPRESS_ERROR_LOW_MEMORY = 3;
    //压缩是吧
    public static final int COMPRESS_ERROR = 4;
    //进度
    public static final int COMPRESS_PERCENT = 5;

    public static final int CANCEL_COMPRESS = 6;

    private int tempPercent = 0;

    public static VideoCompressUtils getInstance() {
        if (null == instance) {
            instance = new VideoCompressUtils();
        }
        return instance;
    }


    /**
     * 压缩视频
     *
     * @param mContext
     * @param filepath
     */
    public void compressVideoResource(Context mContext, long fileSize, final String filepath, final Handler handler) {

        if (TextUtils.isEmpty(filepath)) {
            JLog.e("VideoCompressUtils", "filepath isEmpty   ");
            return;
        }
        int level = getLevel(fileSize);
        JLog.e("VideoCompressUtils", "level =  "+level);
        if (level == 0) {
            Message msg = new Message();
            msg.what = CANCEL_COMPRESS;
            handler.sendMessage(msg);
            return;
        }
        tempPercent = 0;
        final String fileName = getVideoName(filepath);
        final String compressPath = filepath.replace(fileName, "com_" + fileName);
        //PLShortVideoTranscoder初始化，三个参数，第一个context，第二个要压缩文件的路径，第三个视频压缩后输出的路径
        PLShortVideoTranscoder mShortVideoTranscoder = new PLShortVideoTranscoder(mContext, filepath, compressPath);
        MediaMetadataRetriever retr = new MediaMetadataRetriever();
        retr.setDataSource(filepath);
        String height = retr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT); // 视频高度
        String width = retr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH); // 视频宽度
        String rotation = retr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_ROTATION); // 视频旋转方向
        int transcodingBitrateLevel = level;//可以自己选择合适的压缩比例
        mShortVideoTranscoder.transcode(Integer.parseInt(width), Integer.parseInt(height), getEncodingBitrateLevel(transcodingBitrateLevel), false, new PLVideoSaveListener() {
            @Override
            public void onSaveVideoSuccess(String s) {
                File file = new File(compressPath);
//                long fileSize = LocalUtils.getFileSize(file);
                boolean result = rename(compressPath, filepath);
                Message msg = new Message();
                msg.what = COMPRESS_SUCCESS;
                handler.sendMessage(msg);
            }

            @Override
            public void onSaveVideoFailed(final int errorCode) {
                Message msg = new Message();
                switch (errorCode) {
                    case ERROR_NO_VIDEO_TRACK:
                        msg.what = COMPESS_ERROR_NO_VIDEO_TRACK;
//                                ToastUtils.getInstance().showToast("该文件没有视频信息！");
                        break;
                    case ERROR_SRC_DST_SAME_FILE_PATH:
                        msg.what = COMPRESS_ERROR_SRC_DST_SAME_FILE_PATH;
//                                ToastUtils.getInstance().showToast("源文件路径和目标路径不能相同！");
                        break;
                    case ERROR_LOW_MEMORY:
                        msg.what = COMPRESS_ERROR_LOW_MEMORY;
//                                ToastUtils.getInstance().showToast("手机内存不足，无法对该视频进行时光倒流！");
                        break;
                    default:
                        msg.what = COMPRESS_ERROR;
//                                ToastUtils.getInstance().showToast("transcode failed: " + errorCode);
                        break;
                }
                handler.sendMessage(msg);
            }

            @Override
            public void onSaveVideoCanceled() {
                JLog.e("VideoCompressUtils", "onSaveVideoCanceled");
            }

            @Override
            public void onProgressUpdate(float percentage) {
                int per = (int) (100 * percentage);
                if (tempPercent < per) {
                    JLog.e("VideoCompressUtils11", "onProgressUpdate   "+per+"-----tempPercent--"+tempPercent);
                    tempPercent = per;
                    Message msg = new Message();
                    msg.what = COMPRESS_PERCENT;
                    msg.obj = per;
                    handler.sendMessage(msg);
                }
            }
        });
    }

    private int getLevel(long fileSize) {
        if (fileSize > SIZE_300) {
            return 8;
        } else if (fileSize <= SIZE_300 && fileSize > SIZE_150) {
            return 7;
        } else if (fileSize <= SIZE_150 && fileSize > SIZE_50) {
            return 6;
        } else {
            return 5;
        }
    }

    /**
     * 重命名文件
     *
     * @param oldName
     * @param newName
     * @return
     */
    private static boolean rename(String oldName, String newName) {
        File fileNew = new File(newName);
        File file = new File(oldName);
        String temp = newName + "temp";
        if (fileNew.exists()) {
            boolean aa = fileNew.renameTo(new File(temp));
            if (file.renameTo(new File(newName))) {
                File fileTemp = new File(temp);
                fileTemp.delete();
                return true;
            }
        } else if (file.exists()) {
            if (file.renameTo(new File(newName))) {
                return true;
            }
        }
        return false;
    }

    /**
     * 设置压缩质量
     *
     * @param position
     * @return
     */
    private static int getEncodingBitrateLevel(int position) {
        return ENCODING_BITRATE_LEVEL_ARRAY[position];
    }

    /**
     * 以3分钟最大size为300M计算
     *
     * @param size     视频大小
     * @param duration 时长
     * @return
     */
    public static boolean isShoudCompress(long size, long duration) {
        double p = size / duration;
        if (p > COMPRESS_B) {
            return true;
        }
        return false;
    }

    /**
     * 选的越高文件质量越大，质量越好
     */
    public static final int[] ENCODING_BITRATE_LEVEL_ARRAY = {
            500 * 1000,
            800 * 1000,
            1000 * 1000,
            1200 * 1000,
            1600 * 1000,
            2000 * 1000,
            2500 * 1000,
            4000 * 1000,
            8000 * 1000,
            12000 * 1000,
    };

    /**
     * 从Path中截取文件名称
     *
     * @param url
     * @return
     */
    public static String getVideoName(String url) {
        String name = "";
        if (!TextUtils.isEmpty(url)) {
            String[] nList = url.split("/");
            if (null != nList && nList.length > 0) {
                String n = nList[nList.length - 1];
//                int in = n.indexOf(".");
                name = n;//n.substring(0,in);
            }
        }
        return name;
    }
}
